<?php
/**
 * Created by PhpStorm.
 * User: Chris
 * Date: 15/1/19
 * Time: 下午10:07
 */


class Controller_Channel_Weixin extends Controller
{
    /*
1 第一步：用户同意授权，获取code
2 第二步：通过code换取网页授权access_token
3 第三步：刷新access_token（如果需要）
4 第四步：拉取用户信息(需scope为 snsapi_userinfo)
5 附：检验授权凭证（access_token）是否有效
     */

    /**
     * 准备跳转到微信进行资料获取
     */
    public function action_requireLogin(){
        Package::load('weixin');
        $weixinService = new \Koodev\WeixinService();

        // snsapi_base  for open id
        // snsapi_userinfo for fetch detail
        $scope = Input::param('scope', "snsapi_userinfo");

        $nextPage = Input::param('nextPage', Uri::create('mobile/user/'));
        $url  = $weixinService->requestInfoRedirectUrl( $nextPage, $scope );
        Response::redirect($url);
    }


    /**
     * 开发用方法
     */
    public function action_devRedirect(){
        $nextPage = Input::param('nextPage', '');
        $code = Input::param('code', ''); // code
        $state = Input::param('state', '');
//        echo "nextPage[".$nextPage."] code[".$code."] state[".$state."]";
//        return ;
        $url = $nextPage . "&code=".$code."&state=".$state;
        Response::redirect( $url );
    }

    /**
     * weixin 回调 (sns_userinfo)
     */
    public function action_callback(){
        Package::load('weixin');
        $weixinService = new \Koodev\WeixinService();
        $nextPage = Input::param('nextPage', '');
        $code = Input::param('code', ''); // code
        $state = Input::param('state', '');
//        echo "testwx_back!code[".$code."] state[".$state."] nextPage[".$nextPage."]";
        Log::debug("weixin auth callback!code[".$code."] state[".$state."] nextPage[".$nextPage."]");

        $responseInfo = $weixinService->requestAccessToken($code);
//        echo "access_token[".$accessTokenInfo['access_token']."]";

//        echo "Access Token: ". $responseInfo->access_token;
        $openId = $responseInfo->openid;
        Log::debug("Request code[".$code."] accessToken:". $responseInfo->access_token. " Scope[".$responseInfo->scope."] openid[".$openId."]");
//        Log::debug("Request code[".$code."] accessToken:". $responseInfo->access_token. " Scope[".$responseInfo->scope."] openid[".$openId."]");

        Session::set(SESSION_WEIXION_OPENID, $openId);
        if (strstr($responseInfo->scope, "snsapi_userinfo")){
            Log::debug("yes ! has snsapi_userinfo!!");
            // while scope is snsapi_userinfo, we can call api to get user info:
            $userInfoResponse = $weixinService->requestUserInfo($responseInfo->access_token, $responseInfo->openid);

            // everything is ready, save to the session(bind session) and redirect !
            Session::set(SESSION_WEIXION, $userInfoResponse);
        }else{
            Log::debug("no ... has not snsapi_userinfo!!");
        }

        if ($nextPage==''){
            $nextPage = Uri::create('mobile/user/');
        }
        Response::redirect($nextPage);
    }


    public function action_echo(){
        $xml = Input::xml();
//        echo (json_encode($xml));
        $echoStr = Input::param("echostr", "");

        Log::info("Echo start...");
        Log::info(json_encode($xml));
        Log::info("Echo end.");
        echo $echoStr;

    }



}